import Vue from 'vue'
import Router from 'vue-router'
import Layout from '../layout'
import { frameRoutes, frameMenu } from './config'
import menuSetting from '@/menuSet.js'
import store from '@/store'
import { getHomeRouter } from '@/utils/validate.js'

Vue.use(Router)

// console.log(frameRoutes, 'frameRoutes')
// console.log(frameMenu, 'frameMenu')
export const baseRoutes = [
  {
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/pages/system/redirect/index')
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/pages/system/login/index'),
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/pages/system/error/404'),
    hidden: true
  },
  {
    path: '/401',
    component: () => import('@/pages/system/error/401'),
    hidden: true
  },
  {
    path: '/order/scan/detail',
    component: () => import('@/pages/module/order/scan/detail.vue'),
    hidden: true
  }
]

function getAllRouter() {
  if (menuSetting.isLocalRouter) { // 是否获取本地路由
    store.dispatch('permission/setRoutes', frameRoutes)
    store.dispatch('permission/setRoutesAllMenu', frameMenu)
    const homeRouterPath = JSON.parse(getHomeRouter()).path
    baseRoutes.unshift({
      path: '/',
      redirect: homeRouterPath,
      hidden: true,
      component: Layout,
      children: frameRoutes
    })
    baseRoutes.push({ path: '*', redirect: '/404', hidden: true })
  }
  return baseRoutes
}

const createRouter = () =>
  new Router({
    mode: 'history', // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes: getAllRouter()
  })
const router = createRouter()

export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router
